<?php 
namespace struggle;

defined('CORE_PATH') or die('Access Forbidden');

header('Content-type:text/html;charset=utf-8');
error_reporting(E_ALL | E_STRICT);
//error_reporting(0);
date_default_timezone_set('PRC');

version_compare('5.3.0', PHP_VERSION, '<=') or die('PHP version require >= 5.3.0');
//
defined('DIR_SEP')  or define('DIR_SEP',DIRECTORY_SEPARATOR);
defined('PATH_SEP') or define('PATH_SEP',PATH_SEPARATOR);  //;

defined('APP_NAME') or define('APP_NAME', basename(dirname($_SERVER['SCRIPT_NAME'])));
defined('APP_ROOT') or define('APP_ROOT',rtrim(dirname($_SERVER['SCRIPT_FILENAME']),'/').'/');

defined('APP_PATH')    or define('APP_PATH',APP_ROOT.'apps'.DIR_SEP);
defined('APP_CACHE')   or define('APP_CACHE', APP_ROOT.'caches'.DIR_SEP);
defined('APP_BACKEND') or define('APP_BACKEND', APP_ROOT.'admin'.DIR_SEP);
defined('APP_THEME')   or define('APP_THEME',APP_ROOT.'themes'.DIR_SEP);
defined('APP_LIB')     or define('APP_LIB',APP_ROOT.'addones'.DIR_SEP);
defined('APP_CONF')    or define('APP_CONF',APP_ROOT.'config'.DIR_SEP);

//调用register_shutdown_function 中的回调函数后，当前工作目录的相对路径起始根目录变成'/'
//如，调用前为/app/www/htdocs/，调用后为'/'
defined('__ROOT__')       or define('__ROOT__', dirname(__FILE__).'/');
defined('LIB_PATH')       or define('LIB_PATH',CORE_PATH.'libraries/');
defined('CONF_PATH')      or define('CONF_PATH',CORE_PATH.'config/');
defined('THEME_PATH')     or define('THEME_PATH',CORE_PATH.'themes/');
define('IS_WIN',PHP_OS == 'WINNT'?true:false);


class Sle{
    public static $itsError = array();
    
    public static function run(){
        register_shutdown_function('struggle\\Sle::shutdownHandle');
        set_exception_handler('struggle\\Sle::exceptionHandle');
        set_error_handler('struggle\\Sle::errorHandle',E_ALL | E_STRICT);
        
        require CONF_PATH.'functions.php';

        $aCoreFile = array(
            LIB_PATH.'object.php',
            LIB_PATH.'core/controll.php',
            LIB_PATH.'core/view.php', 
            LIB_PATH.'debug.php',
            LIB_PATH.'cache/cache.php',
            LIB_PATH.'cache/driver/file.php',
            LIB_PATH.'log.php',
        );
        
        foreach ($aCoreFile as $sFile){
            require_cache($sFile);
        }
        //加载配置文件
        load_config('config');
        
        //加载字符转换文件
        load_config('zh-cn');

        
        //trigger_error('测试错误',E_USER_ERROR);
        throw new \Exception("测试");
        //new ddd();
    }
    
    
    public static function exceptionHandle($e){
        libraries\Log::save("异常".($e->getCode()?"[{$e->getCode}]":'')."：{$e->getMessage()}  {$e->getFile()} 第{$e->getLine()}行");
        Sle::halt("异常：{$e->getMessage()}");
    } 
    
    public static function errorHandle($errno, $errstr, $errfile, $errline, $errcontext){
        switch ($errno){
            case E_ERROR:
            case E_PARSE:
            case E_COMPILE_ERROR:
            case E_USER_ERROR:
                $sErrInfo = "错误[{$errno}]：{$errstr}\t{$errfile}\t第{$errline}行";
                if (C('app_debug')){
                    self::trace($sErrInfo);
                }
                libraries\Log::save($sErrInfo);
                break;
            case E_WARNING:
            case E_CORE_WARNING:
            case E_COMPILE_WARNING:
            case E_USER_WARNING:
                $sWarnInfo = "警告[{$errno}]：{$errstr}\t{$errfile}\t第{$errline}行";
                if (C('app_debug')){
                    self::trace($sWarnInfo);
                }
                libraries\Log::save($sWarnInfo);
                break;
            case E_NOTICE:
            case E_USER_NOTICE:
                $sNoticeInfo = "通知[{$errno}]：{$errstr}\t{$errfile}\t第{$errline}行";
                if (C('app_debug')){
                    self::trace($sNoticeInfo);
                }
                libraries\Log::save($sNoticeInfo);
                break;
            default:
                $sOtherInfo = "其他[{$errno}]：{$errstr}\t{$errfile}\t第{$errline}行";
                if (C('APP_DEBUG')){
                    self::trace($sOtherInfo);
                }
                libraries\Log::save($sOtherInfo);
        }
        
    } 
    
    public static function shutdownHandle(){
        if($aError = error_get_last()){
            $sErrInfo = "错误[{$aError['type']}]：{$aError['message']}{$aError['file']}第{$aError['line']}行";
            libraries\Log::save($sErrInfo);
            self::halt("错误：{$aError['message']}");
        }
    }
    
    public static function halt($sMsg = '', $sUrl=''){
        $oView = new libraries\core\View();
        $oView -> render(__ROOT__.'');//绝对路径
        if ($sUrl){
            redirect($sUrl, $sMsg);
        }else{
            exit("{$sMsg}");
        }
    }
    
    public static function trace($sTrace){
        static $aTraceMsg = array();
        $aTraceMsg[] = $sTrace;
    }
    
}

function dump(){
    $aParam = func_get_args();
    foreach ($aParam as $mVal){
        var_dump($mVal);
        echo "<br>-------------".date('Y-m-d H:i:s')."--------------------<br />";
    }
}


function load_config($sName){
    static $aConfig = array();
    $sFileName = $sName.'.php';
    if (!isset($aConfig[$sName])){
        $aConfig[$sName] = include CONF_PATH.$sFileName;
        if (file_exists(APP_CONF.$sFileName)){
            $aConfig[$sName] = array_merge($aConfig[$sName], include APP_CONF.$sFileName);
        }
    }
    foreach ($aConfig[$sName] as $sKey => $mVal){
        $sName == 'config' && C($sKey,$mVal);
        $sName == 'zh-cn'  && L($sKey,$mVal);
    }
}

function C($sName, $mVal = null){
    static $aConfig=array();
    if (is_string($sName)){
        if (!strpos($sName, '.')){
            $sName = strtolower($sName);
            if (is_null($mVal)) //不能用empty,否则不能把值设为空
                return isset($aConfig[$sName])?$aConfig[$sName]:null;
            $aConfig[$sName] = $mVal;
        }
    }
}


function L($sName, $mVal = null){
    static $aLang=array();
    if (is_string($sName)){
        if (!strpos($sName, '.')){
            $sName = strtolower($sName);
            if (is_null($mVal)) //不能用empty,否则不能把值设为空
                return isset($aLang[$sName])?$aLang[$sName]:null;
            $aLang[$sName] = $mVal;
        }
    }
}



function buildAppDir(){
    //
}

function errorLevelName($sName){
    static $aLevelMap = array(
        E_ERROR         => '致命运行时错误',                           // 1
        E_WARNING       => '运行时警告，非致命错误',                   // 2
        E_PARSE         => '编译时解析错误',                          // 4
        E_NOTICE        => '运行时通知',                              // 8
        E_CORE_ERROR    => '致命错误，php核心触发',                   // 16 
        E_CORE_WARNING  => '警告，php核心触发',                      // 32 
        E_COMPILE_ERROR => '致命编译时错误，zend脚本引擎触发',          // 64
    );
}

Sle::run();










